import router from "@/router";
import store from "@/store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Loading } from "element-ui";
import setting from "@/settings";
import { registerModule } from "@/utils/common";
import * as msgApi from "@/api/msg";
NProgress.configure({ showSpinner: false });
// 白名单 不校验token
const whiteList = ["/login", "/auth-redirect", "/bind"];
let loadFull = null;
router.beforeEach((to, from, next) => {
  console.log(from.path, to.path);
  // NProgress.start();
  const token = window.$auth.getToken();
  if (token) {
    setting.msg && registerModule(store, msgApi);
    // 设置网页标题
    to.meta.title && store.dispatch("settings/setTitle", to.meta.title);
    /* has token*/
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (!router.options.isAddDynamicMenuRoutes) {
        !loadFull && (loadFull = Loading.service({ fullscreen: true }));
        // 获取租户列表
        if (setting.tenant) {
          try {
            store.dispatch("user/GetTennat");
          } catch (error) {
            //  TODO 处理错误回调
            console.log(error);
          }
        }

        store
          .dispatch("permission/GenerateRoutes")
          .then(() => {
            next({ ...to, replace: true });
          })
          .catch((err) => {
            console.log(err);
            store.dispatch("user/FedLogOut");
            next({ name: "login" });
          })
          .finally(() => {
            loadFull.close();
          });
      } else {
        // 判断是否跳转非子应用公共路由
        if (to.name === "Modules" && !to.meta.modules) {
          next("/404");
        } else {
          next();
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`); // 否则全部重定向到登录页
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
